import React, { Component } from 'react';
import {getCarList,changeNum} from '../../api/car';
import CarItem from '../../components/carItem';

class Car extends Component {
    state = {
        carList:[],
        checkAll:false
    }
    componentDidMount(){
        this.getCarList();
    }

    //获取数据
    getCarList = () => {
        //获取购物车列表
        getCarList().then(res => {
            if(res.data.code === 1){
                let list = res.data.data.map(item => {
                    item.checked = false; //添加选中的状态
                    return item
                })
                this.setState({
                    carList:list
                })
            }
        })
    }
    render() {
        let {carList,checkAll} = this.state;
        return (
            <div>
                <div>
                    {carList.map(item => <CarItem changeStatus={this.changeStatus} changeNum={this.changeNum} key={item.id} {...item}></CarItem>)}
                </div>
                <div>
                    <input type="checkbox" checked={checkAll} onChange={this.checkAll}/>全选
                </div>
            </div>
        );
    }

    //修改数量
    changeNum = (id,num) => {
        console.log(id,num)
        //修改的id num数量
        changeNum(id,num).then(res => {
            console.log(res)
            if(res.data.code === 1){
                this.getCarList();
            }
        })
    }

    //修改状态
    changeStatus = (id,checked) => {

        let list = this.state.carList;

        list.forEach(item => {
            if(item.id === id){
                item.checked = checked;
            }
        })

        let checkAll = list.every(item => item.checked);

        this.setState({
            carList:list,
            checkAll
        })

    }

    //全选中  全不选中

    checkAll = (e) => {
        // e.target.checked //当前的状态
        let list = this.state.carList;
        list.forEach(item => {
            item.checked = e.target.checked;
        })
        this.setState({
            carList:list,
            checkAll:e.target.checked
        })
    }
}

export default Car;